﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AspNetCoreTest.Common
{
    public class ClientErrorFactory : IClientErrorFactory
    {
        private readonly ApiBehaviorOptions _options;

        public ClientErrorFactory(IOptions<ApiBehaviorOptions> options)
        {
            _options = options.Value;
        }

        public IActionResult GetClientError(ActionContext actionContext, IClientErrorActionResult clientError)
        {
            ModelStateDictionary modelState = actionContext.ModelState;
            if (!modelState.IsValid)
            {
                var msg = modelState.FirstOrDefault().Value?.Errors?.FirstOrDefault()?.ErrorMessage;
                return new JsonResult("fail-" + msg);
            }
            return clientError;
        }
    }
}
